package com.cq.androidtools.recycleview.table

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.RelativeLayout
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.cq.androidtools.R
import com.cq.androidtools.recycleview.table2.HorizontalScrollViewContent
import com.cq.androidtools.recycleview.table2.RecyclerViewTop
import com.cq.base.recycleview.base.BaseRVMultiTypeDiffAdapter
import com.cq.base.utils.isTouchPointInView

/**
 * 作者: CQ
 * 日期: 2021-08-03
 * 说明:
 */
class GridRecycleView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr), OnSlideListener {

    // 头部列表
    lateinit var recyclerViewTop: RecyclerViewTop

    // 左侧列表
    lateinit var recyclerViewLeft: RecyclerView

    // 中间列表
    lateinit var recyclerViewContent: RecyclerView

    //
    lateinit var nestedScrollView: NestedScrollView

    lateinit var horizontalScrollViewContent: HorizontalScrollViewContent
    lateinit var horizontalScrollViewContentTop: HorizontalScrollViewContent

    // 头部列表适配器
    private var adapterTop = CommonAdapter()

    // 左侧列表适配器
    private var adapterLeft = CommonAdapter()

    // 中间列表适配器
    private var adapterContent = CommonAdapter()

    // 头部列表数据（横向线行）
    private var listDataTop = mutableListOf<TableDataBean>()

    // 左侧列表数据（纵向线行）
    private var listDataLeft = mutableListOf<TableDataBean>()

    // 中间列表数据（横向网格）
    private var listDataContent = mutableListOf<TableDataBean>()

    // 是否是顶部recycleView移动
    var isIntoTop = false

    // 是否是中间recycleView移动
    var isIntoContent = false

    // 是否是左边recycleVIew移动
    var isIntoLeft = false

    private var onSlideListener: OnSlideListener? = null

    fun setOnSlideListener(onSlideListener: OnSlideListener?) {
        this.onSlideListener = onSlideListener
    }

    init {
        initView()
    }

    @SuppressLint("NewApi")
    private fun initView() { // 加载布局，获取view总布局
        val view = View.inflate(context!!, R.layout.grid_recycleview2, this) // 头部列表
        recyclerViewTop = view.findViewById(R.id.recyclerView_top) // 左侧列表
        recyclerViewLeft = view.findViewById(R.id.recyclerView_left) // 中间列表
        recyclerViewContent = view.findViewById(R.id.recyclerView_content) // 滑动控件
        nestedScrollView = view.findViewById(R.id.nestedScrollView)
        horizontalScrollViewContent = view.findViewById(R.id.horizontalScrollView)
        horizontalScrollViewContentTop = view.findViewById(R.id.horizontalScrollViewTop) // 头部列表设置
        // 定义一个线性布局
        val linearLayoutManager = LinearLayoutManager(context) // 设置横向
        linearLayoutManager.orientation = RecyclerView.HORIZONTAL // 头部列表设置布局器
        recyclerViewTop.layoutManager = linearLayoutManager // 定义一个适配器
        recyclerViewTop.addItemDecoration(LinearItemDecoration(context))
        recyclerViewTop.adapter = adapterTop // 头部列表增加一个滑动监听
        

        // 左侧列表设置
        // 定义一个线性布局
        val linearLayoutManagerLeft = LinearLayoutManager(context) // 设置纵向
        linearLayoutManagerLeft.orientation = RecyclerView.VERTICAL // 左侧列表设置布局器
        recyclerViewLeft.layoutManager = linearLayoutManagerLeft // 定义一个适配器
        recyclerViewLeft.addItemDecoration(LinearItemDecoration(context))

        recyclerViewLeft.adapter = adapterLeft // 左侧列表增加一个滑动监听
        recyclerViewLeft.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy) // 滑动的是左侧列表
                if (!isIntoTop && isIntoLeft && !isIntoContent) { // 头部列表滑动时，关联中间列表同步滑动，由于中间列表上下滑动是NestedScrollView控制的，所以滑动NestedScrollView
                    nestedScrollView.scrollBy(dx, dy)
                    onSlideListener?.onSlide(dx, dy)
                }
            }
        })
        // 双击刷新数据
        adapterLeft.setOnDoubleClickListener { pos ->
            adapterContent.clearLocationMap()
            var diffAll = 0
            var diff = 0 // 变化的值 = 原来横向第一个数据 - 原有数据
            for (i in 0 until listDataContent.size) {
                if (listDataContent[pos].gg2dm == listDataContent[i].gg2dm || listDataContent[i].gg2dm == "合计") {
                    val holder = recyclerViewContent.findViewHolderForAdapterPosition(i) as BaseRVMultiTypeDiffAdapter.MultiTypeViewHolder
                    if (listDataContent[i].type == 2) {
                        diff = listDataContent[pos].value - listDataContent[i].value
                        if (diff == 0) continue
                        diffAll += diff
                        if (holder.getEditText(R.id.item_grid_edit).hasFocus()) {
                            holder.getEditText(R.id.item_grid_edit).clearFocus()
                            holder.getEditText(R.id.item_grid_edit).isFocusable = false
                            holder.getEditText(R.id.item_grid_edit).isFocusableInTouchMode = false
                        }
                        listDataContent[i].value = listDataContent[pos].value
                        adapterContent.notifyItemChanged(i)
                    } else if (listDataContent[i].gg1dm == "合计" && listDataContent[i].gg2dm == "合计") {
                        if (diffAll == 0) continue
                        listDataContent[i].value += diffAll
                        adapterContent.notifyItemChanged(i)
                    } else if (listDataContent[i].gg2dm == "合计") {
                        if (diff == 0) continue
                        listDataContent[i].value += diff
                        adapterContent.notifyItemChanged(i)
                    } else if (listDataContent[i].gg1dm == "合计") {
                        if (diffAll == 0) continue
                        listDataContent[i].value += diffAll
                        adapterContent.notifyItemChanged(i)
                    }
                    Log.e("notifyItemChanged", "notifyItemChanged = ${recyclerViewContent.isLayoutSuppressed}")
                }
            }
        }

        recyclerViewContent.isFocusableInTouchMode = false // 中间列表设置
        val gridLayoutManager = GridLayoutManagerU(context, 3)  // 定义一个网格布局器
        gridLayoutManager.orientation = RecyclerView.HORIZONTAL // 设置网格滑动方向
        recyclerViewContent.layoutManager = gridLayoutManager // 管理布局器
        (recyclerViewContent.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        recyclerViewContent.adapter = adapterContent // 列表关联适配器

        recyclerViewContent.addItemDecoration(GridItemDecoration(context)) // 中间列表设置滑动监听（横向滑动）

        horizontalScrollViewContent.setOnHorizontalScrollChangedListener { x, y ->
            if (!isIntoTop && !isIntoLeft && isIntoContent) {
                horizontalScrollViewContentTop.scrollTo(x, y)
            }
        }

        horizontalScrollViewContentTop.setOnHorizontalScrollChangedListener { x, y ->
            if (isIntoTop && !isIntoLeft && !isIntoContent) { // 头部列表滑动时，关联中间列表同步滑动
                horizontalScrollViewContent.scrollTo(x, y)
            }
        }

        // 中间列表的纵向滑动控件设置滑动监听
        nestedScrollView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, scrollX, scrollY, oldScrollX, oldScrollY -> // 滑动的是中间列表
            if (!isIntoTop && !isIntoLeft && isIntoContent) { // 中间列表纵向滑动时，关联左侧列表纵向滑动
                recyclerViewLeft.scrollBy(scrollX - oldScrollX, scrollY - oldScrollY)
                onSlideListener?.onSlide(scrollX - oldScrollX, scrollY - oldScrollY)
            }
        })
    }

    // 监听手指按下，获取按下的位置，判断按下的位置属于哪个区域
    override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                onSlideListener?.onInitClickState()
                isIntoTop = recyclerViewTop.isTouchPointInView(event.rawX.toInt(), event.rawY.toInt())
                isIntoLeft = recyclerViewLeft.isTouchPointInView(event.rawX.toInt(), event.rawY.toInt())
                isIntoContent = recyclerViewContent.isTouchPointInView(event.rawX.toInt(), event.rawY.toInt()) // 横向或者纵向移动时，布局移动，可以导致按下的位置可能也在中间布局，
                if (isIntoTop || isIntoLeft) {
                    isIntoContent = false
                }
            }
        }
        return super.dispatchTouchEvent(event)
    }

    fun onRefreshRV() {
        adapterTop.onAutoData(listDataTop)
        adapterLeft.onAutoData(listDataLeft)
        val gridL = recyclerViewContent.layoutManager as GridLayoutManagerU
        gridL.spanCount = listDataLeft.size
        recyclerViewContent.layoutManager = gridL
        adapterContent.onAutoData(listDataContent)
    }

    fun setDataTop(list: MutableList<TableDataBean>) { // 主要是添加合计字段
        listDataTop = list
        val topBean = TableDataBean()
        topBean.type = 0
        topBean.gg1dm = "合计"
        listDataTop.add(topBean)

    }

    fun setDataLeft(list: MutableList<TableDataBean>) { // 主要是添加合计字段
        listDataLeft = list
        val leftBean = TableDataBean()
        leftBean.type = 1
        leftBean.gg2dm = "合计"
        listDataLeft.add(leftBean)
    }

    fun setDataContent(list: MutableList<TableDataBean>) {


        listDataContent = list
        val map = mutableMapOf<String, Int>() // gg1和gg2各行各列之间的和（也就是合计了）
        val size = listDataLeft.size * listDataTop.size // 3 * 3 = 9
        for (i in 0 until size) {
            if (listDataContent[i].gg1dm != "合计") {
                if (map.containsKey(listDataContent[i].gg1dm)) { // 计算规格1之间的值
                    map[listDataContent[i].gg1dm] = map[listDataContent[i].gg1dm]!! + listDataContent[i].value
                } else {
                    map[listDataContent[i].gg1dm] = listDataContent[i].value
                }
                if (map.containsKey(listDataContent[i].gg2dm)) { // 计算规格2之间的值
                    map[listDataContent[i].gg2dm] = map[listDataContent[i].gg2dm]!! + listDataContent[i].value
                } else {
                    map[listDataContent[i].gg2dm] = listDataContent[i].value
                }
            }
            val contentBean = TableDataBean()
            contentBean.type = 3
            if (i < listDataLeft.size * (listDataTop.size - 1) && i % listDataLeft.size == listDataLeft.size - 2) { // 增加gg1合计
                contentBean.gg1dm = listDataContent[i].gg1dm
                contentBean.gg2dm = "合计"
                contentBean.value = map[listDataContent[i].gg1dm]!!
                listDataContent.add(i + 1, contentBean)
            } else if (i == size - 1) { // 增加总合计
                listDataContent[i].position = i
                break
            } else if (i >= listDataLeft.size * (listDataTop.size - 1) - 1) { // 增加gg2合计
                val pos = i - (listDataLeft.size * (listDataTop.size - 1) - 1)
                contentBean.gg1dm = "合计"
                contentBean.gg2dm = listDataLeft[pos].gg2dm
                contentBean.value = map[listDataLeft[pos].gg2dm]!!
                listDataContent.add(i + 1, contentBean)
            }
            listDataContent[i].position = i
        }

    }

    fun setDataTopKeep(list: MutableList<TableDataBean>) { // 主要是添加合计字段
        listDataTop = list
        recyclerViewTop.setHasFixedSize(true)
        adapterTop.onAutoData(listDataTop)
    }

    fun setDataLeftKeep(list: MutableList<TableDataBean>) { // 主要是添加合计字段
        listDataLeft = list
        recyclerViewLeft.setHasFixedSize(true)
        adapterLeft.onAutoData(listDataLeft)
    }

    fun setDataContentKeep(list: MutableList<TableDataBean>) {
        val gridL = recyclerViewContent.layoutManager as GridLayoutManagerU
        gridL.spanCount = listDataLeft.size
        recyclerViewContent.layoutManager = gridL
        listDataContent = list
        recyclerViewContent.setHasFixedSize(true)
        adapterContent.onAutoData(listDataContent)
    }

    /**
     * 同步滑动
     */
    override fun onSlide(dx: Int, dy: Int) {
        if (dx != 0) {
            recyclerViewTop.scrollBy(dx, dy)
            recyclerViewContent.scrollBy(dx, dy)
        } else if (dy != 0) {
            recyclerViewLeft.scrollBy(dx, dy)
            nestedScrollView.scrollBy(dx, dy)
        }
    }

    override fun onInitClickState() {
        isIntoTop = false
        isIntoLeft = false
        isIntoContent = false
    }
}


